package com.example.controller;

import com.example.entity.Menu;
import com.example.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/menus")
public class MenuController {

    @Autowired
    private MenuMapper menuMapper;

    // 分页查询所有菜单
    @GetMapping
    public Map<String, Object> getAllMenus(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        try {
            Integer offset = (page - 1) * pageSize;
            List<Menu> menus = menuMapper.findAllMenus(offset, pageSize);
            Long total = menuMapper.countAllMenus();

            result.put("success", true);
            result.put("data", menus);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);
            result.put("totalPages", (total + pageSize - 1) / pageSize);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    // 根据父菜单ID查询子菜单
    @GetMapping("/parent/{parentId}")
    public Map<String, Object> getMenusByParentId(@PathVariable Long parentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Menu> menus = menuMapper.findMenusByParentId(parentId);
            result.put("success", true);
            result.put("data", menus);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }
}
